#ifndef __ANY_H_
#define __ANY_H_

#include <iostream>
#include <algorithm>
#include <cassert>
#include <typeinfo>
#include <unistd.h>
#include <string>
class Any
{
private:
    class holder 
    {
    public:
        ~holder() {}
        virtual const std::type_info& Type()=0;
        virtual holder* Clone()=0;
    };
    template<class T>
    class placeholder: public holder
    {
    public:
        placeholder(const T &val): _val(val) {}
        virtual const std::type_info& Type()
        {
            return typeid(T);
        }
        virtual holder* Clone()
        {
            return new placeholder(_val);
        }
    public: 
        T _val;
    };
private:
    holder *_content;//容器
public:
    Any():_content(nullptr) {}
    template<class T>
    Any(const T& val)
    {
        _content=new placeholder<T>(val);
    }
    Any(const Any& other)
    {
        _content=other._content?other._content->Clone():nullptr;
    }
    ~Any()
    {
        delete _content;
    }
    Any& Swap(Any& other)
    {
        std::swap(_content,other._content);
        return *this;
    }
    template<class T>
    T* Get()
    {
        //想要获取的数据类型，必须和保存的数据类型一致
        assert(typeid(T) == _content->Type());
        return &((placeholder<T>*)_content)->_val;
    }
    template<class T>
    Any& operator=(const T& val)
    {
        //为val构造一个临时对象，进行交换
        Any(val).Swap(*this);
        return *this;
    }
    Any& operator=(const Any& other)
    {
        Any(other).Swap(*this);
        return *this;
    }
};

#endif //__ANY_H_